<script setup lang="ts">
import {
  ElRow,
  ElCol,
  ElAlert,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElMessage
} from "element-plus";
import { ref, onMounted, onUnmounted, watch } from "vue";
import "codemirror/mode/javascript/javascript.js";
import type { CmComponentRef } from "codemirror-editor-vue3";
import { DocumentEditor } from "@onlyoffice/document-editor-vue";
const demoFileUrl = defineModel("demoFileUrl");
interface Props {
  scriptUrl?: string;
}

defineOptions({
  name: "ParagraphMark",
});

const props = withDefaults(defineProps<Props>(), {});

const getUuid = function () {
  return "xxxxxxxxxxxxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};

const VITE_ONLY_OFFICE_BASE_URL = import.meta.env.VITE_ONLY_OFFICE_BASE_URL;
const code = ref(``);
const containerRef = ref();
const cmRef = ref<CmComponentRef>();

let documentEditorKey = ref("");
let containerHeight = 0;
let officeHeight = ref("100%");
let doHeight = ref(false);
onMounted(() => {
  containerHeight = containerRef.value.parentNode.offsetHeight;
  console.log(11, containerHeight);
  containerRef.value.style.height = containerHeight + "px";
  if (containerHeight > 800) {
    containerHeight = 800;
  }
  officeHeight.value = containerHeight + "px";
  doHeight.value = true;
  documentEditorKey.value = getUuid();
});

onUnmounted(() => {
  cmRef.value?.destroy();
});

watch(demoFileUrl, async (newsDemoFileUrl, oldDemoFileUrl) => {});

let sourceConnector = null;
let targetConnector = null;
let targetClickParagraphId = null;
const onDocumentReadySource = () => {
  sourceConnector = DocEditor.instances.source.createConnector();
  sourceConnector.attachEvent("onClickParagraph", function (data) {
    if (data.paragraphId) {
      sourceFindParagraphIndex(data.paragraphId);
    }
  });
};
const onDocumentReadyTarget = () => {
  targetConnector = DocEditor.instances.target.createConnector();
  targetConnector.attachEvent("onClickParagraph", function (data) {
    if (data.paragraphId) {
      targetClickParagraphId = data.paragraphId;
      targetFindParagraphIndex(data.paragraphId);
    }
  });
  targetConnector.attachEvent("onContextMenuShow", (options) => {
    console.log(options);
    if (targetClickParagraphId) {
      targetConnector.addContextMenuItem([
        {
          id: "context_menu_id",
          text: "修改译文",
          data: targetClickParagraphId,
          onClick: (data) => {
            console.log("[CONTEXTMENUCLICK] menuSubItem1: " + data);
            fillTargetTextByTargetId(data);
          },
        },
      ]);
    }
  });
};

var sourceConfig = ref({
  height: officeHeight.value,
  type: "desktop",
  // "type": "mobile",
  documentType: "word",
  historyList: {
    history: [],
    currentVersion: "1",
  },
  document: {
    title: "原文.docx",
    url: "http://47.94.91.67/demo_file/paragraphMarkSource.docx",
    permissions: {
      print: true,
      download: true,
      edit: true,
    },
    fileType: "docx",
    key: getUuid(),
  },
  editorConfig: {
    customization: {
      autosave: false,
      compactToolbar: false,
      forcesave: true,
      toolbarNoTabs: false,
      help: false,
      compactHeader: false,
      hideRightMenu: true,
      plugins: true,
      uiTheme: "theme-light",
      zoom: 70,
      review: {
        trackChanges: true,
      },
    },
    mode: "edit",
    callbackUrl:
      "https://api.docs.onlyoffice.com/dummyCallback",
    lang: "zh-CN",
    user: {
      name: "曹瑞剑雄",
      id: "104",
    },
  },
});

var targetConfig = ref({
  height: officeHeight.value,
  type: "desktop",
  // "type": "mobile",
  documentType: "word",
  historyList: {
    history: [],
    currentVersion: "1",
  },
  document: {
    title: "译文.docx",
    url: "http://47.94.91.67/demo_file/paragraphMarkTarget.docx",
    permissions: {
      print: true,
      download: true,
      edit: true,
    },
    fileType: "docx",
    key: getUuid(),
  },
  editorConfig: {
    customization: {
      autosave: false,
      compactToolbar: false,
      forcesave: true,
      toolbarNoTabs: false,
      help: false,
      compactHeader: false,
      hideRightMenu: true,
      plugins: true,
      uiTheme: "theme-light",
      zoom: 70,
      review: {
        trackChanges: true,
      },
    },
    mode: "edit",
    callbackUrl:
      "https://api.docs.onlyoffice.com/dummyCallback",
    lang: "zh-CN",
    user: {
      name: "曹瑞剑雄",
      id: "104",
    },
  },
});

let sourceFindParagraphIndex = function (paragraphId) {
  Asc.scope = {
    paragraphId: paragraphId,
  };
  sourceConnector.callCommand(
    function () {
      var oDocument = Api.GetDocument();
      var allParagraphs = oDocument.GetAllParagraphs();
      var paragraphIndex = null;
      for (var i = 0; i < allParagraphs.length; i++) {
        var paragraph = allParagraphs[i];
        if (Asc.scope.paragraphId == paragraph.GetId()) {
          paragraphIndex = i;
          break;
        }
      }
      return paragraphIndex;
    },
    function (paragraphIndex) {
      if (paragraphIndex != null) {
        // 原文点击的时候，同步更新一下targetClickParagraphId
        Asc.scope = {
          paragraphIndex: paragraphIndex,
        };
        targetConnector.callCommand(
          function () {
            var oDocument = Api.GetDocument();
            var allParagraphs = oDocument.GetAllParagraphs();
            var paragraphId = null;
            for (var i = 0; i < allParagraphs.length; i++) {
              var paragraph = allParagraphs[i];
              if (Asc.scope.paragraphIndex == i) {
                paragraphId = paragraph.GetId();
                break;
              }
            }
            return paragraphId;
          },
          function (paragraphId) {
            if (paragraphId != null) {
              targetClickParagraphId = paragraphId;
              highLightParagraph(sourceConnector, paragraphIndex);
              highLightParagraph(targetConnector, paragraphIndex);
            }
          }
        );
      }
    }
  );
};

let targetFindParagraphIndex = function (paragraphId) {
  Asc.scope = {
    paragraphId: paragraphId,
  };
  targetConnector.callCommand(
    function () {
      var oDocument = Api.GetDocument();
      var allParagraphs = oDocument.GetAllParagraphs();
      var paragraphIndex = null;
      for (var i = 0; i < allParagraphs.length; i++) {
        var paragraph = allParagraphs[i];
        if (Asc.scope.paragraphId == paragraph.GetId()) {
          console.log(paragraph.GetText());
          paragraphIndex = i;
          break;
        }
      }
      return paragraphIndex;
    },
    function (paragraphIndex) {
      if (paragraphIndex != null) {
        highLightParagraph(sourceConnector, paragraphIndex);
        highLightParagraph(targetConnector, paragraphIndex);
      }
    }
  );
};

/**
 * 设置段落高亮
 * 并且跳转到该位置
 **/
let highLightParagraph = function (connectorInstance, paragraphIndex) {
  Asc.scope = {
    paragraphIndex: paragraphIndex,
  };
  connectorInstance.callCommand(
    function () {
      var oDocument = Api.GetDocument();
      if (oDocument.HighLightParagraphByIndex) {
        oDocument.HighLightParagraphByIndex(
          "index",
          [Asc.scope.paragraphIndex],
          true
        );
      }
    },
    function (paragraphIndex) {}
  );
};

/**
 * 通过译文ID设置译文的text
 * @param paragraphId 译文段落ID
 */
let fillTargetTextByTargetId = function (paragraphId) {
  Asc.scope = {
    paragraphId: paragraphId,
  };
  targetConnector.callCommand(
    function () {
      var oDocument = Api.GetDocument();
      var allParagraphs = oDocument.GetAllParagraphs();
      var paragraphIndex = null;
      let text = null;
      for (var i = 0; i < allParagraphs.length; i++) {
        var paragraph = allParagraphs[i];
        if (Asc.scope.paragraphId == paragraph.GetId()) {
          paragraphIndex = i;
          text = paragraph.GetText({
            Numbering: true,
            Math: true,
            NewLineSeparator: "\r",
            TabSymbol: "\t",
          });
          break;
        }
      }
      return { index: paragraphIndex, text: text };
    },
    function (resultData) {
      if (resultData.index == null) {
        return;
      }
      // 设置译文
      formData.value.engText = resultData.text;
      // 设置原文
      fillSourceTextByTargetIndex(resultData.index);
    }
  );
};

/**
 * 通过译文的index填充原文的text
 * @param targetIndex 译文的index
 */
let fillSourceTextByTargetIndex = function (targetIndex) {
  Asc.scope = {
    targetIndex: targetIndex,
  };
  sourceConnector.callCommand(
    function () {
      var oDocument = Api.GetDocument();
      var allParagraphs = oDocument.GetAllParagraphs();
      var paragraphIndex = null;
      let text = null;
      for (var i = 0; i < allParagraphs.length; i++) {
        var paragraph = allParagraphs[i];
        if (Asc.scope.targetIndex == i) {
          paragraphIndex = i;
          text = paragraph.GetText({
            Numbering: true,
            Math: true,
            NewLineSeparator: "\r",
            TabSymbol: "\t",
          });
          break;
        }
      }
      return { index: paragraphIndex, text: text };
    },
    function (resultData) {
      if (resultData.index == null) {
        return;
      }
      // 设置原文
      formData.value.zhCnText = resultData.text;
      dialogFormVisible.value = true;
    }
  );
};

/**
 * 替换译文文字
 */
let replaceTargetTextByTargetId = function(){
  if(!targetClickParagraphId){
    ElMessage.error('没有选中译文');
    return;
  }
  if(formData.value.replaceText == ''){
    ElMessage.error('请填写需要替换的文本');
    return;
  }
  Asc.scope = {
    paragraphId: targetClickParagraphId,
    replaceText: formData.value.replaceText
  };
  targetConnector.callCommand(
    function () {
      var oDocument = Api.GetDocument();
      var allParagraphs = oDocument.GetAllParagraphs();
      var paragraph = null;
      for (var i = 0; i < allParagraphs.length; i++) {
        paragraph = allParagraphs[i];
        if (Asc.scope.paragraphId == paragraph.GetId()) {
          break;
        }
      }
      if(paragraph){
        paragraph.SetText(Asc.scope.replaceText);
      }
    },
    function () {
      formData.value.zhCnText = "";
      formData.value.engText = "";
      formData.value.replaceText = "";
      dialogFormVisible.value = false;
    }
  );
  
};

const init = function () {
  sourceConfig.value.document.key = getUuid();
};
init();

const dialogVisible = ref(true);
const formLabelWidth = "80px";
const dialogFormVisible = ref(false);
const formData = ref({
  zhCnText: "",
  engText: "",
  replaceText: "",
  remark: ""
});
</script>

<template>
  <di class="onlyoffice_demo_container" ref="containerRef">
    <el-dialog v-model="dialogVisible" show-close="false">
      <el-row style="height: 60px">
        <el-col :span="24">
          <el-alert
            style="height: 30px; font-size: 15px; font-weight: 600"
            title="请点击任意段落，或者点击【译文文档】段落后右键->译文修改"
            type="error"
            closable="false"
          />
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog v-model="dialogFormVisible" title="修改文档" width="800">
      <el-form>
        <el-form-item label="原文" :label-width="formLabelWidth">
          <el-input
            v-model="formData.zhCnText"
            autocomplete="off"
            :rows="3"
            type="textarea"
            disabled
          />
        </el-form-item>
        <el-form-item label="译文" :label-width="formLabelWidth">
          <el-input
            v-model="formData.engText"
            autocomplete="off"
            :rows="3"
            type="textarea"
            disabled
          />
        </el-form-item>
        <el-form-item label="译文修改" :label-width="formLabelWidth">
          <el-input
            v-model="formData.replaceText"
            autocomplete="off"
            :rows="3"
            type="textarea"
          />
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input
            v-model="formData.remark"
            autocomplete="off"
            :rows="3"
            type="textarea"
            placeholder="备注无法写入文档中，目前API不支持"
            disabled
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="replaceTargetTextByTargetId">
            提交
          </el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-row style="height: 100%">
      <el-col :span="12">
        <DocumentEditor
          v-if="doHeight"
          id="source"
          :documentServerUrl="VITE_ONLY_OFFICE_BASE_URL"
          :config="sourceConfig"
          :events_onDocumentReady="onDocumentReadySource"
        />
      </el-col>
      <el-col :span="12" style="height: 100%">
        <DocumentEditor
          v-if="doHeight"
          id="target"
          :documentServerUrl="VITE_ONLY_OFFICE_BASE_URL"
          :config="targetConfig"
          :events_onDocumentReady="onDocumentReadyTarget"
        />
      </el-col>
    </el-row>
  </di>
</template>

<style scoped>
.onlyoffice_demo_container {
  width: 100%;
  height: 100%;
  display: inline-block;
}
.panel-title {
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  margin-bottom: 6px;
  padding: 0 24px;
}
.cross-align-center {
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}
.diff-panel-list .title {
  font-size: 16px;
}
.panel-body {
  padding: 0 24px;
  overflow: auto;
}
.diff-item {
  border: 1px solid rgba(81, 141, 150, 0.2);
  border-radius: 4px;
  margin-top: 12px;
  cursor: pointer;
  padding: 6px 10px 15px;
  background: rgba(232, 234, 239, 0.21);
  border: 1px solid rgba(185, 192, 206, 0.3);
  border-radius: 8px;
}
.diff-item-active {
  border: 1px solid #1c6dff;
  -webkit-box-shadow: 0 0 16px 6px rgba(57, 127, 138, 0.1215686275);
  box-shadow: 0 0 16px 6px rgba(57, 127, 138, 0.1215686275);
}
.cross-align-center {
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}
.bold {
  font-weight: 500;
}
.diff-dot {
  width: 2px;
  height: 14px;
  background: #00bfaf;
  margin-right: 8px;
}
.diff-item-addition .diff-dot {
  background: #1c6dff;
}
.diff-type {
  color: #2f3d59;
}
.diff-content {
  word-break: break-all;
  white-space: break-spaces;
}
.diff-content {
  padding-left: 10px;
  margin-top: 10px;
  line-height: 22px;
  max-height: 154px;
  overflow-y: hidden;
}
.diff-item-deletion .diff-dot,
.diff-item-unfill .diff-dot {
  background: #ec4949;
}
.flex-row {
  -webkit-box-orient: horizontal;
  -ms-flex-direction: row;
  flex-direction: row;
}
.flex-col {
  -webkit-box-orient: vertical;
  -ms-flex-direction: column;
  flex-direction: column;
}
.flex-col,
.flex-row {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-direction: normal;
}
.diff-content .addition {
  color: #1c6dff;
}
.diff-content .deletion {
  color: #ec4949;
  text-decoration: line-through;
}
</style>
